package service

import (
	"fmt"
	"log"
	"os"
	"time"

	"kubernate-server/conf"
	_ "kubernate-server/module"

	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	//"github.com/jinzhu/gorm"
)

var cmsApp *CmsApp

/**
 * Author: ycliud
 * Description: grom propertis
 * Date:20250927
 */

type CmsApp struct {
	db *gorm.DB
}

/*
*
单例获取数据库连接池
*/
func GetCmsApp() *CmsApp {
	if cmsApp == nil {
		cmsApp = &CmsApp{}
		connDB(cmsApp)
	}
	return cmsApp
}

func NewCmsApp() *CmsApp {
	app := &CmsApp{}
	connDB(app)
	return app
}

func connDB(app *CmsApp) {
	/*host := conf.DB.Host
	  port := conf.DB.Port
	  	username := conf.DB.Username
	  	dbname := conf.DB.Dbname
	  	//pathwd = host + ":" + port
	    mysqlDB, err := gorm.Open(mysql.Open(host+":@tcp(127.0.0.1:3306)/cms_account?charset=utf8mb4&parseTime=True&loc=Local"))
	*/
	//mysqlDB, err := gorm.Open(mysql.Open("root:@tcp(127.0.0.1:3306)/cms_account?charset=utf8mb4&parseTime=True&loc=Local"))

	//mysqlDB, err := gorm.Open(mysql.Open(username + ":@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8mb4&parseTime=True&loc=Local"))
	conf.InitConfig("conf/config.yaml")

	host := conf.MyConf.DB.Host
	password := conf.MyConf.DB.Password
	port := conf.MyConf.DB.Port
	username := conf.MyConf.DB.Username
	database := conf.MyConf.DB.Database

	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database)
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	//mysqlDB, err := gorm.Open(driverName, args)
	mysqlDB, err := gorm.Open(mysql.Open(args), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	db, err := mysqlDB.DB()
	if err != nil {
		panic(err)
	}
	db.SetMaxOpenConns(4)
	db.SetMaxIdleConns(2)
	mysqlDB = mysqlDB.Debug()
	app.db = mysqlDB

}

/*
func connOperateAppClient(app *CmsApp) {
	// new etcd client
	client, err := clientv3.New(clientv3.Config{
		Endpoints: []string{"127.0.0.1:2379"},
	})
	if err != nil {
		panic(err)
	}
	dis := etcd.New(client)
	// new etcd client
	endpoint := "discovery:///content_system"
	conn, err := grpc.DialInsecure(
		context.Background(),
		grpc.WithMiddleware(
			recovery.Recovery(),
		),
		grpc.WithEndpoint(endpoint),
		grpc.WithDiscovery(dis),
	)
	if err != nil {
		panic(err)
	}
	appClient := operate.NewAppClient(conn)
	app.operateAppClient = appClient
}

func connRdb(app *CmsApp) {
	// redis-cli
	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	_, err := rdb.Ping(context.Background()).Result()
	if err != nil {
		panic(err)
	}
	app.rdb = rdb
}*/
